package com.flycent.fanbao.adapter;

import java.util.List;

import android.content.Context;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;

import com.flycent.fanbao.R;

public class ListToGridAdapter extends BaseAdapter {
	private List<String> list;
	private Context context;

	public ListToGridAdapter(Context context) {
		this.context = context;
	}

	public void setData(List<String> list) {
		this.list = list;
	}

	@Override
	public int getCount() {
		// 每列两项
		if (list.size() % 2 == 0) {
			return list.size() / 2;
		}
		return list.size() / 2 + 1;
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder viewHolder = null;
		if (convertView == null) {
			viewHolder = new ViewHolder();
			convertView = View.inflate(context, R.layout.item_list_to_grid, null);
			viewHolder.button1 = (Button) convertView
					.findViewById(R.id.item_iamge1);
			viewHolder.button2 = (Button) convertView
					.findViewById(R.id.item_iamge2);

			convertView.setTag(viewHolder);

		} else {
			viewHolder = (ViewHolder) convertView.getTag();
		}
		//position计算  两列的情况下：position* 2 +1 多列依次类推 
		//第一列
		String string1 = list.get(position * 2);

		viewHolder.button1.setText(string1);
		viewHolder.button1.setTag(string1);

		viewHolder.button1.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				Log.d("PAGE", v.getTag().toString());
			}
		});
		//position计算  两列的情况下：position* 2 +1 多列依次类推 
		//第二列
		if ((position * 2 + 1) < list.size()) {
			String string2 = list.get(position * 2 + 1);
			viewHolder.button2.setText(string2);
			viewHolder.button2.setTag(string2);
			viewHolder.button2.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Log.d("PAGE", v.getTag().toString());
				}
			});
		} else {
			//此处可以用一张透明图片替换 避免Grid布局混乱
			viewHolder.button2.setVisibility(View.INVISIBLE);
		}
		return convertView;
	}

	class ViewHolder {

		private Button button1;
		private Button button2;

	}

}
